package main

import (
	"fmt"
	"sync"
)

// 使用共享锁，解决读多写少的问题

// 共享锁
var shareLock sync.RWMutex

// 阻塞
var block1 sync.WaitGroup

func main() {

	var num = 1

	block1.Add(2)
	go read(&num)

	go write(&num)

	block1.Wait()
	fmt.Println(num)

}

// 加一
func read(num *int) {
	for i := 0; i < 50; i++ {
		shareLock.RLock()
		fmt.Println("当前num=", *num)
		shareLock.RUnlock()
	}
	defer block1.Done()
}

// 减少
func write(num *int) {
	for i := 0; i < 50; i++ {
		shareLock.Lock()
		*num = *num + 1
		fmt.Println("值已修改为num = ", *num)
		shareLock.Unlock()
	}
	defer block1.Done()
}
